﻿namespace LiteBlog.Repositories
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Xml.Linq;
    using LiteBlog.Common.Entities;
    using LiteBlog.Repositories.Contracts;
    using LiteBlog.Common.Enums;
    using LiteBlog.Repositories.Framework;
    using LiteBlog.Repositories.Common;
    using System;

    public class ArchiveRepository : StandardRepository<ArchiveMonth>, IArchiveRepository
    {
        public ArchiveRepository(IDataContext context, IXmlHelper xmlHelper)
            : base(context, xmlHelper)
        {
            _path = context.GetPath(DataStoreType.Archive, null);
            _elementName = Elem.Archive;
        }

        private ArchiveMonth GetArchiveMonth(string id)
        {
            ArchiveMonth month = null;
            int archiveId = 0;
            int.TryParse(id, out archiveId);
            if (archiveId > 0)
            {
                month = new ArchiveMonth(archiveId);
            }
            return month;
        }

        protected override XElement GetElement(ArchiveMonth item)
        {
            return new XElement(
                Elem.Archive,
                new XAttribute(Attr.Id, item.Id),
                new XAttribute(Attr.Year, item.Year),
                new XAttribute(Attr.Month, item.Month),
                new XAttribute(Attr.Count, item.Count));
        }

        protected override ArchiveMonth GetEntity(XElement elem)
        {
            var archiveMonth = new ArchiveMonth();
            archiveMonth.Id = (int)elem.Attribute(Attr.Id);
            archiveMonth.Month = (int)elem.Attribute(Attr.Month);
            archiveMonth.Year = (int)elem.Attribute(Attr.Year);
            archiveMonth.Count = (int)elem.Attribute(Attr.Count);
            return archiveMonth;
        }

        protected override void UpdateElement(XElement elem, ArchiveMonth item)
        {
            elem.SetAttributeValue(Attr.Count, item.Count);
        }

        protected override string GetId(ArchiveMonth item)
        {
            return item.Id.ToString();
        }

        protected override void SetId(ArchiveMonth item, string id)
        {
            item.Id = int.Parse(id);
        }
    }
}